#include "string_util.h"

#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <vector>

void StringUtil::HexStrToCharacter(const std::string & data, std::vector<uint8_t> & result_data)
{
    size_t size = data.size();
    for (size_t index = 0; index < size; index += 2)
    {
		uint8_t a = data[index];
		uint8_t b = data[index + 1];
		a = a >= 'a' ? (a - 'a' + 10) : a - '0';
		b = b >= 'a' ? (b - 'a' + 10) : b - '0';
		uint8_t c = (a << 4) | b;
		result_data.push_back(c);
    }
}

void StringUtil::DataToHexStr(const void * data, int data_length, std::string & result)
{
	const uint8_t * ptr = (const uint8_t*)data;
	for (int index = 0; index < data_length; index++)
	{
		uint8_t a = (*(ptr + index)) & 0x0f;
		uint8_t b = (*(ptr + index) & 0xf0) >> 4;

		a = a >= 10 ? ((a - 10 + 'a')) : a + '0';
		b = b >= 10 ? ((b - 10 + 'a')) : b + '0';

		result.push_back(b);
		result.push_back(a);
	}
}

uint16_t StringUtil::BeToH16(uint16_t data)
{
	uint16_t dst = 0;
	BeToHN((uint8_t*)&dst,(uint8_t*)&data, sizeof(uint16_t));
	return dst;
}

uint32_t StringUtil::BeToH32(uint32_t data)
{
	uint32_t dst = 0;
	BeToHN((uint8_t*)&dst, (uint8_t*)&data, sizeof(uint32_t));
	return dst;
}

uint64_t StringUtil::BeToH64(uint64_t data)
{
	uint64_t dst = 0;
	BeToHN((uint8_t*)&dst, (uint8_t*)&data, sizeof(uint64_t));
	return dst;
			   
}

uint16_t StringUtil::HtoBe16(uint16_t data)
{
	uint16_t dst = 0;
	BeToHN((uint8_t*)&dst, (uint8_t*)&data, sizeof(uint16_t));
	return dst;
}

uint32_t StringUtil::HtoBe32(uint32_t data)
{
	uint32_t dst = 0;
	BeToHN((uint8_t*)&dst, (uint8_t*)&data, sizeof(uint32_t));
	return dst;
}

uint64_t StringUtil::HtoBe64(uint64_t data)
{
	uint64_t dst = 0;
	BeToHN((uint8_t*)&dst, (uint8_t*)&data, sizeof(uint64_t));
	return dst;
}

void StringUtil::BeToHN(uint8_t * dst, const uint8_t * src, int length)
{
	for (int index = 0; index < length; index++)
	{
		*(dst + length - index - 1) = *(src + index);
	}
}

